package com.tanhua.dubbo.api;

import com.mongodb.client.result.DeleteResult;
import com.tanhua.model.db.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    //保存喜欢
    @Override
    public String saveUserLike(Long userId, Long likeUserId) {
        Query query = Query.query( Criteria.where( "userId" ).is( userId ).and( "likeUserId" ).is( likeUserId ) );
        if (mongoTemplate.count( query, UserLike.class )>0){
            return null;
        }
        UserLike userLike = new UserLike(  );
        userLike.setId( ObjectId.get() );
        userLike.setLikeUserId( likeUserId );
        userLike.setCreated( System.currentTimeMillis() );
        userLike.setUserId( userId );
        mongoTemplate.save( userLike );
        return userLike.getId().toHexString();
    }
    //互相喜欢
    @Override
    public Boolean isMutualLike(Long userId, Long likeUserId) {
        Criteria criteria1 = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
        Criteria criteria2 = Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId);

        Criteria criteria = new Criteria().orOperator(criteria1, criteria2);
        return this.mongoTemplate.count(Query.query(criteria), UserLike.class) == 2;
    }
    //删除喜欢
    @Override
    public Boolean deleteUserLike(Long userId, Long likeUserId) {
        Query query = Query.query( Criteria.where( "userId" ).is( userId )
                .and( "likeUserId" ).is( likeUserId ) );
        DeleteResult deleteResult = mongoTemplate.remove( query, UserLike.class );
        return deleteResult.getDeletedCount()==1;
    }
}
